﻿namespace Hidistro.UI.SaleSystem.CodeBehind
{
    using Hidistro.Core;
    using Hidistro.Core.Configuration;
    using Hidistro.Membership.Context;
    using Hidistro.Membership.Core;
    using Hidistro.Membership.Core.Enums;
    using Hidistro.Messages;
    using Hidistro.UI.Common.Controls;
    using System;
    using System.Globalization;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using wnxd.Web;

    public class ForgotPassword_new : HtmlTemplatedWebControl
    {
        private int status = 0;
        private string verifyCodeKey = "VerifyCode";
        protected override void AttachChildControls()
        {
            PageTitle.AddSiteNameTitle("找回密码");
            if (status == 1)
            {
                object obj = this.Page.Session["wnxd"];
                if (obj != null)
                {
                    string email = obj.ToString();
                    Web wnxd_web = (Web)this.FindControl("wnxd_web");
                    Literal l = (Literal)this.FindControl("email");
                    wnxd_web.AddScript("Email = \"" + email + "\";");
                    l.Text = email;
                }
                else
                {
                    this.Page.Response.Redirect(this.Page.Request.Url.AbsolutePath);
                }
            }
        }
        protected override void OnInit(EventArgs e)
        {
            this.Page.Response.Redirect("http://account.x-juse.com/ForgotPassword.aspx?sdomain=" + HttpUtility.UrlEncode("http://" + this.Page.Request.Url.Authority));
            if (this.SkinName == null)
            {
                int.TryParse(this.Page.Request.QueryString["status"], out status);
                switch (status)
                {
                    case 0:
                        {
                            this.SkinName = "Skin-ForgotPassword_new.html";
                            this.Page.Session.Remove("wnxd");
                            break;
                        }
                    case 1:
                        {
                            this.SkinName = "Skin-ForgotPassword_new_1.html";
                            break;
                        }
                    case 2:
                        {
                            this.SkinName = "Skin-ForgotPassword_new_2.html";
                            break;
                        }
                }
            }
            base.OnInit(e);
        }
        protected void CheckEmail(Page Page)
        {
            Control form = this.FindControl("wnxd");
            bool error = false;
            string email = (email = Page.Request.Form["ForgotPassword$ctl01"]) == null ? "" : email.Trim();
            IUser user = Users.FindUserByUsername(email);
            if (user == null || user.UserRole == UserRole.SiteManager || user.UserRole == UserRole.Anonymous)
            {
                HtmlGenericControl div = (HtmlGenericControl)form.FindControl("yxmsg");
                div.InnerText = "该邮箱不存在";
                div.Visible = true;
                error = true;
            }
            string verifycode = (verifycode = Page.Request.Form["verifycode"]) == null ? "" : verifycode.Trim();
            if (!this.CheckVerifyCode(verifycode))
            {
                HtmlGenericControl div = (HtmlGenericControl)form.FindControl("vcmsg");
                div.InnerText = "验证码输入错误";
                div.Visible = true;
                error = true;
            }
            if (!error)
            {
                Web wnxd_web = (Web)this.FindControl("wnxd_web");
                string str;
                SiteSettings siteSettings = HiContext.Current.SiteSettings;
                string emailCode = HiContext.Current.CreateVerifyCode(6);
                string body = string.Format("亲爱的{0}：<br>您好！感谢您使用{1}。<br>您正在进行账户基础信息维护，请在校验码输入框中输入：{2}，以完成操作。 <br>注意：此操作可能会修改您的密码、登录邮箱或绑定手机。如非本人操作，请及时登录并修改密码以保证账户安全。（工作人员不会向您索取此校验码，请勿泄漏！） ", user.Username, siteSettings.SiteName, emailCode);
                switch (Messenger.SendMail("验证码", body, user.Email, siteSettings, out str))
                {
                    case SendStatus.NoProvider:
                    case SendStatus.ConfigError:
                        {
                            wnxd_web.AddScript("alert(\"后台设置错误，请自行联系后台管理员\");");
                            break;
                        }
                    case SendStatus.Fail:
                        {
                            wnxd_web.AddScript("alert(\"发送失败\");");
                            break;
                        }
                    case SendStatus.Success:
                        {
                            Page.Session["wnxd"] = email;
                            Page.Response.Redirect(Page.Request.Url.AbsolutePath + "?status=1");
                            break;
                        }
                }
            }
        }
        private bool CheckVerifyCode(string verifyCode)
        {
            if (HttpContext.Current.Request.Cookies[this.verifyCodeKey] == null)
            {
                return false;
            }
            return (string.Compare(HiCryptographer.Decrypt(HttpContext.Current.Request.Cookies[this.verifyCodeKey].Value), verifyCode, true, CultureInfo.InvariantCulture) == 0);
        }
        protected void CheckEmailVerifyCode(Page Page)
        {
            Control form = this.FindControl("wnxd");
            bool error = false;
            string password = (password = Page.Request.Form["password"]) == null ? "" : password.Trim();
            if (password.Length < Membership.Provider.MinRequiredPasswordLength || password.Length > HiConfiguration.GetConfig().PasswordMaxLength)
            {
                HtmlGenericControl div = (HtmlGenericControl)form.FindControl("pwmsg");
                div.InnerText = string.Format("密码的长度只能在{0}和{1}个字符之间", Membership.Provider.MinRequiredPasswordLength, HiConfiguration.GetConfig().PasswordMaxLength);
                div.Visible = true;
                error = true;
            }
            string verifycode = (verifycode = Page.Request.Form["verifycode"]) == null ? "" : verifycode.Trim();
            if (!HiContext.Current.CheckVerifyCode(verifycode))
            {
                HtmlGenericControl div = (HtmlGenericControl)form.FindControl("vcmsg");
                div.InnerText = "邮箱验证码错误";
                div.Visible = true;
                error = true;
            }
            if (!error)
            {
                IUser user = Users.FindUserByUsername(this.Page.Session["wnxd"].ToString());
                bool flag;
                if (user is Member)
                {
                    flag = (user as Member).ChangePasswordWithoutAnswer(password);
                }
                else
                {
                    flag = user.ChangePassword(password);
                }
                if (flag)
                {
                    Messenger.UserPasswordForgotten(user, password);
                    this.Page.Session.Remove("wnxd");
                    this.Page.Response.Redirect(Globals.GetSiteUrls().UrlData.FormatUrl("ForgotPasswordSuccess") + string.Format("?UserName={0}", user.Username));
                }
                else
                {
                    ((Web)this.FindControl("wnxd_web")).AddScript("alert(\"登录密码修改失败，请重试\");");
                }
            }
        }
    }
}

